﻿using MediatR;
using Microsoft.Extensions.Logging;
using MS.Data.API.Read.Command.User;
using MS.Data.API.Read.DTO;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Read.CommandHandle.User
{
    public class GetUserCommandHandler : IRequestHandler<GetUserCommand, APIResult<ApiPagging<UserDTO>>>
    {
        private readonly IBaseRepository<Domain.User> repository;

        public GetUserCommandHandler(IBaseRepository<Domain.User> repository)
        {
            this.repository = repository;
        }
        public Task<APIResult<ApiPagging<UserDTO>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPagging<UserDTO>> result = new APIResult<ApiPagging<UserDTO>>();
            result.code = APIEnum.显示成功;
            result.mes = APIEnum.显示成功.ToString();

            var list = from a in repository.GetAll()
                       where !a.IsDel
                       select new UserDTO
                       {
                           UserId = a.UserId,
                           UserPwd = a.UserPwd,
                           UserName = a.UserName,
                           Phone = a.Phone,
                           NickName = a.NickName,
                           Time = a.Time,
                           State = a.State,
                           IsDel = a.IsDel,
                           RoleNames = a.RoleNames,
                       };

            if(!string.IsNullOrEmpty(request.UserName))
            {
                list = list.Where(x => x.UserName.Contains(request.UserName));
            }


            int totalcount = list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            list = list.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize);
            ApiPagging<UserDTO> page = new ApiPagging<UserDTO>();

            page.TotalPage = totalpage;
            page.TotalCount = totalcount;
            page.Items = list.ToList();
            result.data = page;
            return Task.FromResult(result);

        }
    }
}
